package com.yt.setclaim.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yt.setclaim.models.entity.ClaimClose;
import com.yt.setclaim.models.entity.FinancialPay;
import com.yt.setclaim.models.service.ClaimCloseService;
import com.yt.setclaim.models.vo.FinancialPayVO;
import com.yt.setclaim.server.mapper.ClaimCloseMapper;
import com.yt.setclaim.server.mapper.FinancialPayMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ClaimCloseServiceImpl extends ServiceImpl<ClaimCloseMapper, ClaimClose> implements ClaimCloseService {
    
    private final FinancialPayMapper financialPayMapper;
    
    public ClaimCloseServiceImpl(FinancialPayMapper financialPayMapper) {
        this.financialPayMapper = financialPayMapper;
    }
    
    @Override
    public ClaimClose getByPayId(Integer payId) {
        return this.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ClaimClose>()
                .eq("pay_id", payId)
                .eq("is_delete", 0));
    }
    
    @Override
    public List<FinancialPayVO> getPendingPayments() {
        // 获取所有已支付但未结案的财务支付记录
        // 1. 首先获取所有财务支付记录
        QueryWrapper<FinancialPay> payQueryWrapper = new QueryWrapper<>();
        payQueryWrapper.eq("is_delete", 0); // 未删除
        List<FinancialPay> financialPays = financialPayMapper.selectList(payQueryWrapper);
        
        // 2. 过滤掉已经进行过结案的记录
        List<FinancialPayVO> pendingPayments = new ArrayList<>();
        for (FinancialPay pay : financialPays) {
            // 检查是否已经结案过
            ClaimClose existingClose = this.getOne(new QueryWrapper<ClaimClose>()
                    .eq("pay_id", pay.getPayId())
                    .eq("is_delete", 0));
            
            // 如果还没有结案，则添加到待结案列表中
            if (existingClose == null) {
                FinancialPayVO vo = new FinancialPayVO();
                BeanUtils.copyProperties(pay, vo);
                // ID转换为字符串类型
                vo.setPayId(String.valueOf(pay.getPayId()));
                vo.setCalcId(String.valueOf(pay.getCalcId()));
                vo.setAdminId(String.valueOf(pay.getAdminId()));
                // 业务字段转换为字符串类型
                if (pay.getPayAmount() != null) {
                    vo.setPayAmount(String.valueOf(pay.getPayAmount()));
                }
                if (pay.getAdjustAmount() != null) {
                    vo.setAdjustAmount(String.valueOf(pay.getAdjustAmount()));
                }
                pendingPayments.add(vo);
            }
        }
        
        return pendingPayments;
    }
}